package utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.junit.Test;

public class DateUtil {
	
	public static final String DEFAULT_FORMAT = "yyyy-MM-dd";
	
	public static String fommatYMD(Date date){
		if(date == null)
			return "";
		return String.format("%1$tY-%1$tm-%1$td", date);
	}
	
	/***
	 * 默认格式的现在日期
	 * 
	 * @return
	 */
	public static Date now() {
		return new Date();
	}
	
	/***
	 * yyyy-MM-dd 格式的现在日期
	 * 
	 * @return
	 */
	public static Date today() {
		return formatDate(DEFAULT_FORMAT, now());
	}
	
	/***
	 * yyyy-MM-dd 格式的日期
	 * 
	 * @return
	 */
	public static Date getTomorrow() {
		Calendar c = convertToCalendar(today());
		c.add(Calendar.DAY_OF_MONTH, 1);
		return c.getTime();
	}
	/**
	 * 获取当前时间的上个月时间
	 * @param date
	 * @return
	 */
	public static Date getLastMonth(){
		Calendar calendar = Calendar.getInstance(); 
		calendar.add(Calendar.MONTH, -1);
		return calendar.getTime();
	}
	/**
	 * 往当前时间上加天数
	 * @param date
	 * @param day
	 * @return
	 */
	public static Date getNextDay(Date date,int day){
	     Calendar calendar = Calendar.getInstance();
	     calendar.setTime(date); 
	     calendar.add(calendar.DATE,day);//把日期往后增加一天.整数往后推,负数往前移动 
	     return calendar.getTime();
	}
	
	/***
	 * 按照指定的格式格式化日期
	 * 
	 * @return
	 */
	public static Date formatDate(String format, Date date) {
		SimpleDateFormat formater = new SimpleDateFormat();
		formater.applyPattern(format);
		formater.setLenient(false);
		try {
			return formater.parse(formater.format(date));
		} catch (ParseException e) {
			return now();
		}
	}
	/**
	 * 默认格式 格式化日期
	 * @param date
	 * @return
	 */
	public static Date formatDate(Date date){
		return formatDate(DEFAULT_FORMAT,date);
	}
	
	public static Calendar convertToCalendar(Date date) {
		if (date == null) {
			return null;
		}
		Calendar result = Calendar.getInstance();
		result.setTime(date);
		return result;
	}
	

}
